<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert title="注意 : 只允许为第三级分类设置参数！" type="warning" show-icon :closable="false"/>
      <el-row style="margin-top: 15px; margin-bottom: 15px;">
        <el-col>
          <span>
            选择商品分类 :
          </span>
          <el-cascader :options="cateList"
                       :show-all-levels="false"
                       :props="cascaderProps"
                       v-model="selectedKeys"
                       @change="handleChange"
          />
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button size="small" type="primary" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加参数
          </el-button>
          <el-table :data="manyTableData"
                    border stripe
                    v-if="activeName === 'many'"
                    row-key="sttr_id"
          >

            <el-table-column type="expand">
              <template v-slot:default="scope">
                <el-tag
                    style="margin-left: 10px"
                    v-for="(item, i ) in scope.row.attr_vals"
                    :key="i"
                    closable
                    @close="handleClose(i,scope.row)"
                >
                  {{ item }}
                </el-tag>

                <el-input
                    v-if="scope.row.inputVisible"
                    ref="InputRef"
                    v-model="scope.row.inputValue"
                    size="small"
                    style="margin-left: 15px; width: 150px"
                    @keyup.enter="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                />
                <el-button
                    style="margin-left: 15px"
                    type=""
                    v-else
                    size="small" @click="showInput(scope.row)">
                  + New Tag
                </el-button>
              </template>
            </el-table-column>

            <el-table-column type="index" label="#"/>
            <el-table-column label="参数名称" prop="attr_name"/>
            <el-table-column label="操作">
              <template v-slot:default="scope">
                <el-button type="primary" :icon="Edit" size="small" @click="showEditDialog(scope.row.attr_id)">编辑
                </el-button>
                <el-button type="danger" :icon="Delete" size="small" @click="removeParams(scope.row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button size="small" type="primary" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加属性
          </el-button>
          <el-table :data="onlyTableData" border stripe v-if="activeName === 'only'">
            <el-table-column type="expand">
              <template v-slot:default="scope">
                <el-tag
                    style="margin-left: 10px"
                    v-for="(item, i ) in scope.row.attr_vals"
                    :key="i"
                    closable
                    @close="handleClose(i,scope.row)"
                >
                  {{ item }}
                </el-tag>

                <el-input
                    v-if="scope.row.inputVisible"
                    ref="InputRef"
                    v-model="scope.row.inputValue"
                    size="small"
                    style="margin-left: 15px; width: 150px"
                    @keyup.enter="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                />
                <el-button
                    style="margin-left: 15px"
                    type=""
                    v-else
                    size="small" @click="showInput(scope.row)">
                  + New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"/>
            <el-table-column label="参数名称" prop="attr_name"/>
            <el-table-column label="操作">
              <template v-slot:default="scope">
                <el-button type="primary" :icon="Edit" size="small" @click="showEditDialog">编辑</el-button>
                <el-button type="danger" :icon="Delete" size="small" @click="removeParams(scope.row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

    </el-card>

    <el-dialog
        v-model="addDialogVisible"
        :title="'添加' + titleText"
        width="50%"
        @close="addDialogClosed"
    >

      <el-form
          ref="addFormRef"
          :model="addForm"
          status-icon
          :rules="addFormRules"
          label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"/>
        </el-form-item>
      </el-form>

      <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addParams">
          确定
        </el-button>
      </span>
      </template>
    </el-dialog>

    <el-dialog
        v-model="editDialogVisible"
        :title="'修改' + titleText"
        width="50%"
        @close="editDialogClosed"
    >

      <el-form
          ref="editFormRef"
          :model="editForm"
          status-icon
          :rules="editFormRules"
          label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"/>
        </el-form-item>
      </el-form>

      <template #footer>
      <span class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editParams">
          确定
        </el-button>
      </span>
      </template>
    </el-dialog>


  </div>
</template>

<script>
import {Delete, Edit} from "@element-plus/icons-vue";

export default {
  name: "Params",
  data() {
    return {
      cateList: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
      },
      selectedKeys: [],
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      addDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          {required: true, message: '请输入参数名称', trigger: 'blur'}
        ]
      },
      editDialogVisible: false,
      editForm: {
        attr_name: ''
      },
      editFormRules: {
        attr_name: [
          {required: true, message: '请输入参数名称', trigger: 'blur'}
        ]
      },
      inputVisible: false,
      inputValue: '',


    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const {data: res} = await this.$http.get('/categories')
      if (res.meta.status === 200) {
        this.cateList = res.data
      }
      return (res.meta.status === 200) ? this.$message.success(res.meta.msg) : this.$message.error(res.meta.msg);
    },
    async handleChange() {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return this.$message.error('无法选择该选项')
      } else {
        await this.getParamsData()
      }

    },
    handleClick() {
      console.log(this.activeName)
      setTimeout(function () {
      }, 1000);
      this.getParamsData()
    },
    async getParamsData() {
      const {data: res} = await this.$http.get(`/categories/${this.selectedKeys[2]}/attributes`,
          {params: {sel: this.activeName}})

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals !== '' ? item.attr_vals.split(',') : [];
        item.inputVisible = false;
        item.inputValue = '';
      })


      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    addParams() {
      this.$refs.addFormRef.validate(async v => {
        if (v) {

          const {data: res} = await this.$http.post(`/categories/${this.selectedKeys[2]}/attributes`,
              {
                attr_name: this.addForm.attr_name,
                attr_sel: this.activeName,
              })
          if (res.meta.status === 201) {
            this.$message.success(res.meta.msg)
            await this.getParamsData()
            this.addDialogVisible = false
          } else {
            return this.$message.error(res.meta.msg);
          }
        }
      })
    },
    async showEditDialog(attr_id) {
      const {data: res} = await this.$http.get(`/categories/${this.selectedKeys[2]}/attributes/${attr_id}`, {
        params: {
          attr_sel: this.activeName
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      } else {
        this.editForm.attr_name = res.data.attr_name
        this.editForm = res.data
      }

      this.editDialogVisible = true
    },
    editParams() {
      this.$refs.editFormRef.validate(async v => {
        if (v) {
          const {data: res} = await this.$http.put(`/categories/${this.selectedKeys[2]}/attributes/${this.editForm.attr_id}`, {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          })

          if (res.meta.status === 200) {
            await this.getParamsData()
            this.editDialogVisible = false
          }

          return (res.meta.status === 200) ? this.$message.success(res.meta.msg) : this.$message.error(res.meta.msg);
        }
      })
    },
    removeParams(attr_id) {
      this.$confirm(
          '此操作将永久删除该参数, 请确认！',
          '警告',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(async () => {
        const {data: res} = await this.$http.delete(`/categories/${this.selectedKeys[2]}/attributes/${attr_id}`);
        if (res.meta.status !== 200) {
          this.$message.warning(res.meta.msg)
        } else {
          await this.getParamsData()
          this.$message.success(res.meta.msg)
        }

      }).catch(() => {
        this.$message.info('已取消删除操作');
      })
    },
    async handleInputConfirm(s) {
      await this.saveAttrVals(s)
    },

    showInput(s) {
      s.inputVisible = true

      this.$nextTick(_ => {
        this.$refs.InputRef.$refs.input.focus();
      })

    },
    handleClose(i, s) {
      s.attr_vals.splice(i, 1)
      this.saveAttrVals(s)
    },
    async saveAttrVals(s) {

      const {data: res} = await this.$http.put(`/categories/${this.selectedKeys[2]}/attributes/${s.attr_id}`, {
        attr_name: s.attr_name,
        attr_sel: s.attr_sel,
        attr_vals: s.attr_vals.join(',')
      });

      console.log(res)
    }


  },
  computed: {
    Delete() {
      return Delete
    },
    Edit() {
      return Edit
    },
    isBtnDisabled() {
      return !(this.selectedKeys.length >= 3);
    },
    titleText() {
      return this.activeName === 'many' ? '动态参数' : '静态参数';
    }
  }
}
</script>

<style scoped>

</style>